use super::config;
pub use tklog::{
    async_debug, async_error, async_fatal, async_info, async_trace, async_warn, Format, ASYNC_LOG,
    LEVEL, MODE,
};
use tokio;

fn is_open_log() -> bool {
    unsafe {
        return config::OPEN_LOG;
    }
}

/// Initialize log service
/// This function must be called before any log function
/// log level: Trace < Debug < Info < Warn < Error < Fatal
/// -----------------------------------------------------------------
/// If the option to enable logging is configured
/// the logging service will be initialized by server.start() at the beginning of the server
pub async fn init() {
    unsafe {
        if is_open_log() {
            ASYNC_LOG
                .set_console(config::DEBUG)
                .set_level(config::LOG_LEVEL)
                .set_format(Format::LevelFlag | Format::Time)
                .set_cutmode_by_time(
                    config::LOG_FILE,
                    MODE::DAY,
                    config::LOG_FILE_MAX_NUM,
                    true,
                )
                .await;
        }
    }
}

pub fn trace<T>(arg: T)
where
    T: std::fmt::Display + Send + 'static,
{
    if is_open_log() {
        tokio::spawn(async move {
            async_trace!(arg);
        });
    }
}

pub fn debug<T>(arg: T)
where
    T: std::fmt::Display + Send + 'static,
{
    if is_open_log() {
        tokio::spawn(async move {
            async_debug!(arg);
        });
    }
}

pub fn info<T>(arg: T)
where
    T: std::fmt::Display + Send + 'static,
{
    if is_open_log() {
        tokio::spawn(async move {
            async_info!(arg);
        });
    }
}
pub fn warn<T>(arg: T)
where
    T: std::fmt::Display + Send + 'static,
{
    if is_open_log() {
        tokio::spawn(async move {
            async_warn!(arg);
        });
    }
}

pub fn error<T>(arg: T)
where
    T: std::fmt::Display + Send + 'static,
{
    if is_open_log() {
        tokio::spawn(async move {
            async_error!(arg);
        });
    }
}

pub fn fatal<T>(arg: T)
where
    T: std::fmt::Display + Send + 'static,
{
    if is_open_log() {
        tokio::spawn(async move {
            async_fatal!(arg);
        });
    }
}
